package com.tim.helper;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tim.util.StringAnalysisUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import javax.script.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * http工具类，回显数据
 */
public class HttpHelper {

    @Test// 打印表格对象头
    public void printTableHeader() throws IOException {
        String path = "";
        List<String> list = Files.readAllLines(Paths.get(path));
        String title = "";
        String code = "";
        Map<String, String> map = new LinkedHashMap<>();
        for(String line : list){
            String trim = line.trim();
            if(trim.startsWith("@ApiModelProperty")){
                title = StringAnalysisUtil.getAnnoValue(line).trim();
            }else if(trim.startsWith("private ")){
                code = StringAnalysisUtil.getFieldName(line).trim();
                map.put(code, title.substring(0, Math.min(8, title.length())));
            }
        }
        List<Map> headers = new ArrayList<>();
        map.forEach((k,v)->{
            Map<String, String> map1 = MapUtil.builder("title", v)
                    .put("code", k)
                    .build();
            headers.add(map1);
        });
        System.out.println(JSON.toJSONString(headers));
    }

    String contextPath = "";

    @Test
    public void req() throws ScriptException {
        // 1-本地统一对账
        use1();
        String path = "";
        int isGet = 0;// 0-POST 1-GET
        String reqBody = "";// json对象
        // js表达式
        String expr = "";

        // 执行请求
        String url = contextPath+path;
        Method method = isGet==1 ? Method.GET : Method.POST;
        HttpRequest request = HttpUtil.createRequest(method, url)
                .header("contentType", "application/json")
                .body(reqBody);
        String respBody = request.execute().body();
        if(StringUtils.isNotBlank(expr)){
            JSONObject jsonObject = JSON.parseObject(respBody);
            //获得javascript的脚本引擎
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("javascript");
            //进行脚本编译
            CompiledScript compiledScript = ((Compilable) scriptEngine).compile(expr);
            //绑定java的参数
            Bindings bindings = new SimpleBindings(jsonObject);
            //执行并打印结果
            Object obj = compiledScript.eval(bindings);
            respBody = JSON.toJSONString(obj);
        }

        System.out.println(respBody);
    }

    @Test
    public void pageToExcel() {
        String url = "";
        int isGet = 0;// 0-POST 1-GET
        String reqBody = "";// json对象
        // js表达式
        String targetExpr = "";// 直接填属性
        String fields = "";// 逗号分隔

        StringBuilder builder = new StringBuilder();
        for (int page = 0; ; page++) {
            // 执行请求
            Method method = isGet==1 ? Method.GET : Method.POST;
            HttpRequest request = HttpUtil.createRequest(method, url)
                    .header("contentType", "application/json")
                    .header("Cookie","")
//                .header("token","")
                    .body(reqBody.replace("", ""+page));
            String respBody = request.execute().body();
            JSONObject jsonObject = JSON.parseObject(respBody);
            JSONArray targetArr = null;
            String[] split = targetExpr.trim().split("\\.");
            for (int i = 0; i <split.length; i++) {
                String str = split[i].trim();
                boolean isArray = str.contains("[");
                if(isArray){
                    int index = str.indexOf('[');
                    JSONArray jsonArray = jsonObject.getJSONArray(str.substring(0, index));
                    if(i== split.length-1){
                        targetArr=jsonArray;
                    }else{
                        jsonObject = jsonArray.getJSONObject(Integer.parseInt(str.substring(index+1, str.indexOf("]"))));
                    }
                }else{
                    jsonObject = jsonObject.getJSONObject(str);
                }
            }
            if(targetArr!=null&& !targetArr.isEmpty()){
                String[] infos = fields.replaceAll("\\s", "")
                        .split(",");
                for (int i = 0; i < targetArr.size(); i++) {
                    JSONObject targetObj = targetArr.getJSONObject(i);
                    for(String info : infos){
                        builder.append(targetObj.getString(info)).append("\t");
                    }
                    builder.append("\n");
                }
            }else{
                break;
            }
        }
        System.out.println(builder);

    }


    @Test
    public void pageHeader() {
        String info = "";
        info = info.replaceAll("<[^>]+>", "\t")
                .replaceAll("\t+", "\t")
                .trim();
        System.out.println(info);
    }

    private void use1(){
        contextPath = "";
    }

}
